<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/18 19:54
 */

namespace module\user\logic;

use module\user\front\input\AvatarInput;
use module\user\model\User;
use mof\annotation\Inject;
use mof\exception\LogicException;
use mof\interface\UserInterface;
use mof\Logic;
use mof\Module;

class ProfileLogic extends Logic
{
    #[Inject(User::class)]
    protected $model;

    public function saveAvatar(UserInterface|Module $user, AvatarInput $avatarInput): string
    {
        $path = $avatarInput->saveToStorage();
        $user->save(['avatar' => $path]);
        return storage_url($path);
    }

    public function unbind(UserInterface|User $user, string $type, string $account): bool
    {
        $oldAccount = $user->getAttr($type);
        if (!$oldAccount) throw new LogicException('没有找到已绑定信息');
        if ($oldAccount !== $account) throw new LogicException('解绑信息不一致');
        //解绑
        $user->save([$type => '']);
        return true;
    }

    public function bind(UserInterface|User $user, string $type, string $account): bool
    {
        $oldAccount = $user->getAttr($type);
        if ($oldAccount) throw  new LogicException('请先解绑再绑定');
        //绑定
        $user->save([$type => $account]);
        return true;
    }
}